﻿namespace WebAppHangfire.Service
{
    /// <summary>
    /// 配置帮助类
    /// </summary>
    public static class ConfigHelper
    {
        /// <summary>
        /// 环境变量名称
        /// </summary>
        public static string AppEnvironmentName { get; set; }
        /// <summary>
        /// 批量载入配置文件
        /// </summary>
        /// <param name="configurationManager"></param>
        /// <param name="files">配置文件名称，省略.json扩展名</param>
        /// <param name="root">配置文件所在路径，默认在configs</param>
        /// <param name="optional">是否是必选</param>
        /// <param name="reloadOnChange">是否自动重载</param>
        /// <returns></returns>
        public static IConfiguration Load(this IConfigurationBuilder configurationManager, List<string> files, string root = "configs", bool optional = true, bool reloadOnChange = true)
        {
            for (int i = 0; i < files.Count; i++)
            {
                string path = files[i];
                if (!string.IsNullOrEmpty(root))
                {
                    path = $"{root}/{path}.json";
                }
                configurationManager.AddJsonFile(path, optional: optional, reloadOnChange: reloadOnChange);
                if (!string.IsNullOrEmpty(ConfigHelper.AppEnvironmentName))
                {
                    configurationManager.AddJsonFile($"{root}/{files[i]}.{ConfigHelper.AppEnvironmentName}.json", optional: optional, reloadOnChange: reloadOnChange);
                }

            }

            return configurationManager.Build();
        }
        /// <summary>
        /// 获得配置信息
        /// </summary>
        /// <param name="fileName">文件名称</param>
        /// <param name="section">节点名称</param>
        /// <returns></returns>
        public static T GetConfigModel<T>(string fileName = "", string section = "") where T : class, new()
        {
            //加载配置文件
            ConfigurationManager configurationManager = new ConfigurationManager();
            var configuration = configurationManager.Load(new List<string> { fileName });
            if (configuration == null)
                return new T();
            if (!string.IsNullOrWhiteSpace(section))
            {
                return configuration.GetSection(section).Get<T>();//返回配置文件内需要的节点
            }
            return configuration.Get<T>();//返回配置文件内需要的节点
        }
    }
}
